package com.cygsunri.util;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

public class JxlUtil {

    public static void DownLoadExcel(HttpServletRequest request, HttpServletResponse response, String filePath, String excelName) {
        try {
            // 下载Excel文件
            response.setHeader("Pragma", "No-cache");
            response.setHeader("Cache-Control", "no-store");
            response.setDateHeader("Expires", 0);
            try (ServletOutputStream outStream = response.getOutputStream()) {
                response.reset();
                String fileName = new String(excelName.getBytes("GBK"), "ISO8859_1");
                /*if (!System.getProperties().getProperty("os.name").startsWith("Windows")) {
                    fileName = new String(excelName.getBytes("ISO8859_1"), "GBK");
                }*/
                if (!request.getHeader("User-Agent").contains("Windows")) {
                    fileName = new String(excelName.getBytes("ISO8859_1"), "GBK");
                }
                response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
                response.setContentType("application/octet-stream; charset=utf-8");
                InputStream blobStream = new FileInputStream(new File(filePath));
                byte[] buffer = new byte[100 * 1024];
                int nbytes = 0;
                while ((nbytes = blobStream.read(buffer)) != -1) {
                    outStream.write(buffer, 0, nbytes);
                }
                blobStream.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
